from django.http import JsonResponse
from util.ImageUtil import *
from util.RandomUtil import *
import face_recognition
import cv2 as cv
import numpy as np
import pymysql
import json


#人脸图片存储路径
face_url= "D:\\Python\\project\\ai-training\\faceImages"
# todo 改路径，改成自己的
#李煊豪的路径face_url= "V:\\pycharm2024.1.4\\py_workspace\\faceImages"


#人脸信息采集
from django.http import JsonResponse
import json
import cv2 as cv
import face_recognition

def face_collection(request):
    if request.method == 'POST':
        # 获取人脸图片矩阵
        image_array = get_image_array(request)
        print(image_array)

        # 人脸图像转化为rgb格式
        image = cv.cvtColor(image_array, cv.COLOR_BGR2RGB)

        # 获取人脸位置
        face_locations = face_recognition.face_locations(image)

        if len(face_locations) == 0:
            return JsonResponse({
                "code": "502",
                "msg": "未检测到人脸!"
            })

        # 获取图片二进制码
        image_byte = get_image_byte(request)

        # 创建图片名称
        fileName = generate_unique_random(min_num=1, max_num=100)

        # 文件写入人脸识别图片，wb表示二进制写入
        with open(os.path.join(face_url, str(fileName)) + ".jpg", "wb") as fp:
            fp.write(image_byte)

        # 数据转换为字典
        data = json.loads(request.body.decode('utf-8'))
        print(data)

        # 获取用户输入的信息
        name = data.get('name')
        age = data.get('age')
        phone = data.get('phone')

        result = face_insert(fileName, name, age, phone)

        if result:
            return JsonResponse({
                "code": "200",
                "msg": "成功"
            })
        else:
            return JsonResponse({
                "code": "500",
                "msg": "数据库插入失败"
            })

    # 非 POST 请求
    return JsonResponse({
        "code": "400",
        "msg": "请求方式错误！"
    })


#人脸信息验证
def face_verify(request):
    if request.method == 'POST':
        #获取人脸图片矩阵
        image_array = get_image_array(request)
        print(image_array)
        #人脸图像转化为rgb格式
        image = cv.cvtColor(image_array, cv.COLOR_BGR2RGB)
        #获取人脸位置
        face_locations = face_recognition.face_locations(image)

        if len(face_locations) == 0:
            return JsonResponse({
                "code": "502",
                "msg": "未检测到人脸!"
            })
        else:
            face_dir = os.listdir(face_url)
            videoFace_vector = face_recognition.face_encodings(image)[0]
            for face in face_dir:
                #定义路径
                face_path = os.path.join(face_url, face)
                face_image = face_recognition.load_image_file(face_path)
                #获取图像编码
                face_vector = face_recognition.face_encodings(face_image)[0]
                #计算相似度
                d = np.linalg.norm(videoFace_vector - face_vector)
                if d < 0.5:
                    #查询个人信息
                    num = int(face.split('.')[0])
                    result = query_info(num)
                    data = {
                        "code": "200",
                        "msg": f"匹配图片编号{face},姓名为{result[0][1]}"
                    }
                    return JsonResponse(data)

            data = {
                "code": "502",
                "msg": "未匹配到人脸!"
            }
            return JsonResponse(data)
    else:
        data={
            "code":"400",
            "msg":"请求方式错误！"
        }
        return JsonResponse(data)


#数据库写入
def face_insert(id,name,age,phone):
    try:
        connection = pymysql.connect(host='119.29.249.72',port=3306,user='root', password='123456cdut', database='facedetection',
                                     charset='utf8')
        #创建游标对象
        cursor = connection.cursor()
        #创建sql语句
        sql = "INSERT INTO user_info (id,user_name,age,phone) VALUES (%s,%s,%s,%s)"
        #执行sql语句
        cursor.execute(sql,(id,name,age,phone))
        #提交事务
        connection.commit()
        print ("插入成功")
        return True
    except Exception as e:
        print("插入失败")
        #回滚事务
        connection.rollback()
        return False
def query_info(id):
    try:
        connection = pymysql.connect(host='119.29.249.72',port=3306,user='root', password='123456cdut', database='facedetection',
                                     charset='utf8')
        #创建游标对象
        cursor = connection.cursor()
        #创建sql语句
        sql = "select * from user_info where id='%s'"
        #执行sql语句
        cursor.execute(sql,(id))
        result=cursor.fetchall()
        return result
        #提交事务
        connection.commit()
        print ("插入成功")
        return True
    except Exception as e:
        print("插入失败")
        #回滚事务
        connection.rollback()
        return False